{% extends "admin/base.html" %}

{% block content %}
<div class="jumbotron">
	<div class="container">
		<h1>设置面板</h1>
	</div>
</div>
<div class="container">
	<div class="row">
		<div class="col-md-3">
			<ul class="nav nav-pills flex-column">
				<li class="nav-item">
					<a class="nav-link rounded-0 active" href="#appearance-section" aria-controls="appearance-section" role="tab" data-toggle="tab">欢迎信息</a>
				</li>
				<li class="nav-item">
					<a class="nav-link rounded-0" href="#accounts-section" aria-controls="accounts-section" role="tab" data-toggle="tab">成员权限</a>
				</li>
				<li class="nav-item">
					<a class="nav-link rounded-0" href="#email-section" aria-controls="email-section" role="tab" data-toggle="tab">邮箱服务器设置</a>
				</li>
				<li class="nav-item">
					<a class="nav-link rounded-0" href="#ctftime-section" aria-controls="ctftime-section" role="tab" data-toggle="tab">比赛时间设置</a>
				</li>
				<li class="nav-item">
					<a class="nav-link rounded-0" href="#backup-section" aria-controls="backup-section" role="tab" data-toggle="tab">视图设置</a>
				</li>
			</ul>
		</div>
		<div class="col-md-9">
			<form method="POST" enctype="multipart/form-data" autocomplete="off" class="w-100">
			{% for error in errors %}
				<div class="alert alert-danger alert-dismissable" role="alert">
					<span class="sr-only">错误:</span>
					{{ error }}
					<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
							aria-hidden="true">×</span></button>
				</div>
			{% endfor %}
			<input id="nonce" name='nonce' type='hidden' value="{{ nonce }}">

			<div class="tab-content">
				<div role="tabpanel" class="tab-pane active" id="appearance-section">
					<div class="form-group">
						<label for="ctf_name">CTF 名称:</label>
						<input class="form-control" id='ctf_name' name='ctf_name' type='text' placeholder="CTF Name"
							   {% if ctf_name is defined and ctf_name != None %}value="{{ ctf_name }}"{% endif %}>
					</div>

					<div class="form-group">
						<label for="ctf_logo">CTF Logo:</label>

						{% if ctf_logo %}
						<div class="d-block py-3">
							<img id="ctf_logo_preview" class="img-responsive ctf_logo" src="{{ request.script_root }}/files/{{ ctf_logo }}"
								 height="25">
							<button type="button" class="btn-sm btn-danger float-right" onclick="
								$('#ctf_logo').attr('placeholder', 'Logo will be removed on next update');
								$('#ctf_logo').attr('value', '');
								$('#ctf_logo').attr('readonly', 'true');
								$('#ctf_logo_preview').css('visibility', 'hidden');
								$(this).text('Logo will be removed on next update');
							">
								Remove Logo
							</button>
						</div>
						{% endif %}

						<input class="form-control" id="ctf_logo_file" name='ctf_logo_file' type='file' placeholder="CTF Logo">
						<input id='ctf_logo' name='ctf_logo' type='hidden' value="{% if ctf_logo is defined %}{{ ctf_logo }}{% endif %}"
							   placeholder="CTF Logo">
					</div>

					<div class="form-group">
						<label for="ctf_theme">主题:</label>
						<select class="form-control" id="ctf_theme" name="ctf_theme">
							<option>{{ ctf_theme_config }}</option>
							{% for theme in themes %}
								<option>{{ theme }}</option>
							{% endfor %}
						</select>
					</div>

					<div class="form-check">
						<label>
							<input id="workshop_mode" name="workshop_mode" type="checkbox"
								   {% if workshop_mode %}checked{% endif %}>
							隐蔽模式 <i class="far fa-question-circle text-muted cursor-help" data-toggle="tooltip"
											 data-placement="right"
											 title="隐藏所有队伍的分数信息."></i>
						</label>
					</div>

					<div class="form-check">
						<label>
							<input id="paused" name="paused" type="checkbox"
								   {% if paused %}checked{% endif %}>
							暂停比赛 <i class="far fa-question-circle text-muted cursor-help" data-toggle="tooltip"
										 data-placement="right"
										 title="此时不能提交任何答案，但依然能查看题目。"></i>
						</label>
					</div>

					<div class="form-check">
						<label>
							<input id="hide_scores" name="hide_scores" type="checkbox" {% if hide_scores %}checked{% endif %}>
							禁止查看积分板
						</label>
					</div>

					<div class="form-group">
						<label>CSS 编辑器</label>
						<textarea class="form-control" id="css-editor" name="css" rows="7">{{ css|default('', True) }}</textarea>
					</div>
				</div>
				<div role="tabpanel" class="tab-pane" id="accounts-section">
					<div class="form-check">
						<label>
							<input id="verify_emails" name="verify_emails" type="checkbox" {% if verify_emails %}checked{% endif %}>
							只允许已验证电子邮件的用户使用平台
						</label>
					</div>

					<div class="form-check">
						<label>
							<input id="view_challenges_unregistered" name="view_challenges_unregistered" type="checkbox" {% if view_challenges_unregistered %}checked{% endif %}>
							未注册的用户可以查看题目
						</label>
					</div>

					<div class="form-check">
						<label>
							<input id="view_scoreboard_if_authed" name="view_scoreboard_if_authed" type="checkbox"
								   {% if view_scoreboard_if_authed %}checked{% endif %}>
								只有登录用户才能查看积分板
						</label>
					</div>

					<div class="form-check">
						<label>
							<input id="prevent_registration" name="prevent_registration" type="checkbox" {% if prevent_registration %}checked{% endif %}>
								禁止注册
						</label>
					</div>

					<div class="form-check">
						<label>
							<input id="prevent_name_change" name="prevent_name_change" type="checkbox" {% if prevent_name_change %}checked{% endif %}>
								禁止修改姓名
						</label>
					</div>
				</div>
				<div role="tabpanel" class="tab-pane" id="email-section">
					<ul class="nav nav-tabs mb-3" role="tablist">
						<li class="nav-item" class="active">
							<a class="nav-link active" href="#mailserver" aria-controls="mailserver" role="tab" data-toggle="tab">邮件服务模式</a>
						</li>
						<li class="nav-item">
							<a class="nav-link" href="#mailgun" aria-controls="mailgun" role="tab" data-toggle="tab">Mailgun模式</a>
						</li>
					</ul>

					<div class="form-group">
						<label>邮箱服务器地址:</label>
						<input class="form-control" id='mailfrom_addr' name='mailfrom_addr' type='text'
								placeholder="Email address used to send email"
								{% if mailfrom_addr is defined and mailfrom_addr != None %}value="{{ mailfrom_addr }}"{% endif %}>
					</div>

					<div class="tab-content">
						<div role="tabpanel" class="tab-pane active" id="mailserver">

							<div class="form-group">
								<label>发信服务器地址:</label>
								<input class="form-control" id='mail_server' name='mail_server' type='text'
										placeholder="Mail Server Address"
										{% if mail_server is defined and mail_server != None %}value="{{ mail_server }}"{% endif %}>
							</div>

							<div class="form-group">
								<label>发信服务器端口:</label>
								<input class="form-control" id='mail_port' name='mail_port' type='text'
										placeholder="Mail Server Port"
										{% if mail_port is defined and mail_port != None %}value="{{ mail_port }}"{% endif %}>
							</div>
							<div class="form-check">
							<label>
								<input id="mail_useauth" name="mail_useauth" type="checkbox" {% if mail_useauth %}checked{% endif %}>
								使用邮件服务器用户名和密码
								</label>
							</div>
							<div id="mail_username_password">
								<div class="form-group">
									<label>用户名:</label>
									{% if mail_username is defined and mail_username != None %}
										<label for="mail_u"><sup>用户名已经被设置</sup></label>
									{% endif %}
									<input class="form-control" id='mail_u' name='mail_u' autocomplete='off' type='text'
											placeholder="Username">
								</div>
								<div class="form-group">
									<label for="mail_p">Password:</label>
									{% if mail_password is defined and mail_password != None %}
										<label for="mail_p"><sup>密码已经被设置</sup></label>
									{% endif %}
									<input class="form-control" id='mail_p' name='mail_p' autocomplete='off' type='password'
											placeholder="Password">
								</div>
								<sup>取消选中设置并更新以删除用户名和密码</sup>
								<br>
								<br>
							</div>
							<div class="form-check">
								<label>
									<input id="mail_ssl" name="mail_ssl" type="checkbox" {% if mail_ssl %}checked{% endif %}>
									SSL
								</label>
							</div>
							<div class="form-check">
								<label>
									<input id="mail_tls" name="mail_tls" type="checkbox" {% if mail_tls %}checked{% endif %}>
									TLS
								</label>
							</div>
						</div>
						<div role="tabpanel" class="tab-pane" id="mailgun">

							<div class="form-group">
								<label>Mailgun API Base URL:</label>
								<input class="form-control" id='mg_base_url' name='mg_base_url' type='text'
										placeholder="Mailgun API Base URL"
										{% if mg_base_url is defined and mg_base_url != None %}value="{{ mg_base_url }}"{% endif %}>
							</div>
							<div class="form-group">
								<label>Mailgun API Key:</label>
								<input class="form-control" id='mg_api_key' name='mg_api_key' type='text'
										placeholder="Mailgun API Key"
										{% if mg_api_key is defined and mg_api_key != None %}value="{{ mg_api_key }}"{% endif %}>
							</div>
						</div>
					</div>
				</div>
				<div role="tabpanel" class="tab-pane" id="ctftime-section">
					<ul class="nav nav-tabs mb-3">
						<li class="nav-item">
							<a class="nav-link active" href="#start-date" aria-controls="start-date" role="tab" data-toggle="tab">开始时间</a>
						</li>
						<li class="nav-item">
							<a class="nav-link" href="#end-date" aria-controls="end-date" role="tab" data-toggle="tab">结束时间</a>
						</li>
						<li class="nav-item">
							<a class="nav-link" href="#freeze-date" aria-controls="freeze-date" role="tab" data-toggle="tab">冻结时间</a>
						</li>

					</ul>

					<div class="tab-content">
						<div role="tabpanel" class="tab-pane active" id="start-date">
							<div class="row" id="start-date">
								<div class="col-md-12">
									<p>这是比赛开始的时间，题目将自动解锁，用户将能够提交答案。</p>
									<sub class="text-right mb-3">* 所有时间字段都需要填写</sub>
								</div>

								<div class="form-group col-md-2">
									<label for="start-month">月份:</label>
									<input class="form-control start-date" id='start-month' name='start-month' min="0" max="12" type='number'>
								</div>

								<div class="form-group col-md-2">
									<label for="start-day">日期:</label>
									<input class="form-control start-date" id='start-day' name='start-day' min="0" max="31" type='number'>
								</div>

								<div class="form-group col-md-3">
									<label for="start-year">年份:</label>
									<input class="form-control start-date" id='start-year' name='start-year' type='number'>
								</div>

								<div class="form-group col-md-2">
									<label for="start-hour">小时:</label>
									<input class="form-control start-date" id='start-hour' name='start-hour' min="0" max="23" type='number'>
								</div>

								<div class="form-group col-md-3">
									<label for="start-minute">分钟:</label>
									<input class="form-control start-date" id='start-minute' name='start-minute' min="0" max="59" type='number'>
								</div>

								<div class="form-group col-md-12">
									<label for="start-timezone">时区:</label>
									<select class="form-control start-date" id="start-timezone">
										<script>
											document.write('<option>' + moment.tz.guess() + '</option>');
											var tz_names = moment.tz.names();
											for (var i = 0; i < tz_names.length; i++) {
												document.write('<option>' + tz_names[i] + '</option>');
											}
										</script>
									</select>
								</div>

								<div class="form-group col-md-12">
									<label for="start-local">当地时间:</label>
									<input class="form-control" id='start-local' type='text'
											placeholder="Start Date (Local Time)" readonly>
								</div>

								<div class="form-group col-md-12">
									<label for="start-zonetime">时区时间:</label>
									<input class="form-control" id='start-zonetime' type='text'
											placeholder="Start Date (Timezone Time)" readonly>
								</div>

								<div class="form-group col-md-12">
									<label>UTC时间戳:</label>
									<input class="form-control" id='start' name='start' type='text'
										placeholder="Start Date (UTC timestamp)"
										{% if start is defined and start != None %}value="{{ start }}"{% endif %} readonly>
								</div>
							</div>
						</div>
						<div role="tabpanel" class="tab-pane" id="end-date">
							<div class="row" id="end-date">
								<div class="col-md-12">
									<p>这是比赛结束的时间， 题目将自动关闭，用户将无法提交答案。</p>
									<sub class="text-right mb-3">* 所有时间字段都需要填写</sub>
								</div>

								<div class="form-group col-md-2">
									<label for="end-month">月份:</label>
									<input class="form-control end-date" id='end-month' name='end-month' min="0" max="12"
											type='number'>
								</div>

								<div class="form-group col-md-2">
									<label for="end-day">日期:</label>
									<input class="form-control end-date" id='end-day' name='end-day' min="0" max="31"
											type='number'>
								</div>

								<div class="form-group col-md-4">
									<label for="end-year">年份:</label>
									<input class="form-control end-date" id='end-year' name='end-year' type='number'>
								</div>

								<div class="form-group col-md-2">
									<label for="end-hour">小时:</label>
									<input class="form-control end-date" id='end-hour' name='end-hour' min="0" max="23"
											type='number'>
								</div>

								<div class="form-group col-md-2">
									<label for="end-minute">分钟:</label>
									<input class="form-control end-date" id='end-minute' name='end-minute' min="0"
											max="59" type='number'>
								</div>

								<div class="form-group col-md-12">
									<label for="end-timezone">时区:</label>
									<select class="form-control end-date" id="end-timezone">
										<script>
											document.write('<option>' + moment.tz.guess() + '</option>');
											var tz_names = moment.tz.names();
											for (var i = 0; i < tz_names.length; i++) {
												document.write('<option>' + tz_names[i] + '</option>');
											}
										</script>
									</select>
								</div>

								<div class="form-group col-md-12">
									<label for="end-local">当地时间:</label>
									<input class="form-control" id='end-local' type='text'
											placeholder="End Date (Local Time)" readonly>
								</div>

								<div class="form-group col-md-12">
									<label for="end-zonetime">时区时间:</label>
									<input class="form-control" id='end-zonetime' type='text'
											placeholder="End Date (Timezone Time)" readonly>
								</div>

								<div class="form-group col-md-12">
									<label for="end">UTC 时间戳:</label>
									<input class="form-control" id='end' name='end' type='text'
											placeholder="End Date (UTC timestamp)"
											{% if end is defined and end != None %}value="{{ end }}"{% endif %} readonly>
								</div>
							</div>
						</div>
						<div role="tabpanel" class="tab-pane" id="freeze-date">
							<div class="row" id="freeze-date">
								<div class="col-md-12">
									<p>冻结时间指定竞赛将被冻结的时间点，所有的提交将会被记录，但新的分数变化将不会显示给用户。</p>
									<sub class="text-right mb-3">* 所有时间字段都需要填写</sub>
								</div>

								<div class="form-group col-md-2">
									<label for="freeze-month">月份:</label>
									<input class="form-control freeze-date" id='freeze-month' name='freeze-month' min="0" max="12"
										   type='number'>
								</div>

								<div class="form-group col-md-2">
									<label for="freeze-day">日期:</label>
									<input class="form-control freeze-date" id='freeze-day' name='freeze-day' min="0" max="31"
										   type='number'>
								</div>

								<div class="form-group col-md-4">
									<label for="freeze-year">年份:</label>
									<input class="form-control freeze-date" id='freeze-year' name='freeze-year' type='number'>
								</div>

								<div class="form-group col-md-2">
									<label for="freeze-hour">小时:</label>
									<input class="form-control freeze-date" id='freeze-hour' name='freeze-hour' min="0" max="23"
										   type='number'>
								</div>

								<div class="form-group col-md-2">
									<label for="freeze-minute">分钟:</label>
									<input class="form-control freeze-date" id='freeze-minute' name='freeze-minute' min="0"
										   max="59" type='number'>
								</div>

								<div class="form-group col-md-12">
									<label for="freeze-timezone">时区:</label>
									<select class="form-control freeze-date" id="freeze-timezone">
										<script>
											document.write('<option>' + moment.tz.guess() + '</option>');
											var tz_names = moment.tz.names();
											for (var i = 0; i < tz_names.length; i++) {
												document.write('<option>' + tz_names[i] + '</option>');
											}
										</script>
									</select>
								</div>

								<div class="form-group col-md-12">
									<label for="freeze-local">当地时间:</label>
									<input class="form-control" id='freeze-local' type='text'
										   placeholder="Freeze Date (Local Time)" readonly>
								</div>

								<div class="form-group col-md-12">
									<label for="freeze-zonetime">时区时间:</label>
									<input class="form-control" id='freeze-zonetime' type='text'
										   placeholder="Freeze Date (Timezone Time)" readonly>
								</div>

								<div class="form-group col-md-12">
									<label for="freeze">UTC 时间戳:</label>
									<input class="form-control" id='freeze' name='freeze' type='text'
										   placeholder="Freeze Date (UTC timestamp)"
										   {% if freeze is defined and freeze != None %}value="{{ freeze }}"{% endif %} readonly>
								</div>
							</div>
						</div>
					</div>

					<div class="form-check">
						<label>
							<input id="view_after_ctf" name="view_after_ctf" type="checkbox" {% if view_after_ctf %}checked{% endif %}>
							在CTF结束之后允许查看题目！
						</label>
					</div>
				</div>
				<div role="tabpanel" class="tab-pane" id="backup-section">
					<ul class="nav nav-tabs mb-3" role="tablist">
						<li class="nav-item active">
							<a class="nav-link active" href="#export-ctf" aria-controls="export-ctf" role="tab" data-toggle="tab">Export</a>
						</li>
						<li class="nav-item">
							<a class="nav-link" href="#import-ctf" aria-controls="import-ctf" role="tab" data-toggle="tab">Import</a>
						</li>
					</ul>
					<div class="tab-content">
						<div role="tabpanel" class="tab-pane active" id="export-ctf">
							<div class="form-group">
								<div class="form-check">
									<label>
										<input class="export-config" value="challenges" type="checkbox" checked> Challenges
									</label>
								</div>
								<div class="form-check">
									<label>
										<input class="export-config" value="teams" type="checkbox" checked> Teams
									</label>
								</div>
								<div class="form-check">
									<label>
										<input class="export-config" value="both" type="checkbox" checked> Solves, Wrong Keys, Unlocks
									</label>
								</div>
								<div class="form-check">
									<label>
										<input class="export-config" value="metadata" type="checkbox" checked> Configuration
									</label>
								</div>
								<a href="{{ request.script_root }}/admin/export" id="export-button" class="btn btn-warning">Export</a>
							</div>
						</div>
						<div role="tabpanel" class="tab-pane" id="import-ctf">
							<div class="form-group">
								<label for="container-files">Import File</label>
								<input class="form-control-file" type="file" name="backup" id="import-file" accept=".zip">
							</div>

							<div class="form-group">
								<div class="form-check">
									<label>
										<input class="import-config" value="challenges" type="checkbox" checked> Challenges
									</label>
								</div>
								<div class="form-check">
									<label>
										<input class="import-config" value="teams" type="checkbox" checked> Teams
									</label>
								</div>
								<div class="form-check">
									<label>
										<input class="import-config" value="both" type="checkbox" checked> Solves, Wrong Keys, Unlocks
									</label>
								</div>
								<div class="form-check">
									<label>
										<input class="import-config" value="metadata" type="checkbox" checked> Configuration
									</label>
								</div>
								<input id="import-button" type="submit" class="btn btn-warning" value="Import">
							</div>
						</div>
					</div>
				</div>
				<button type="submit" id="submit" tabindex="5"
						class="btn btn-md btn-primary float-right">Update
				</button>
			</div>
			</form>
		</div>
	</div>
</div>
{% endblock %}

{% block scripts %}
	<script>
		var months = {
			'January': 1,
			'February': 2,
			'March': 3,
			'April': 4,
			'May': 5,
			'June': 6,
			'July': 7,
			'August': 8,
			'September': 9,
			'October': 10,
			'November': 11,
			'December': 12,
		};
		function load_timestamp(place, timestamp){
			if (typeof timestamp == "string"){
				var timestamp = parseInt(timestamp);
			}
			var m = moment(timestamp * 1000);
			console.log('Loading ' + place);
			console.log(timestamp);
			console.log(m.toISOString());
			console.log(m.unix());
			var month = $('#' + place + '-month').val(m.month() + 1); // Months are zero indexed (http://momentjs.com/docs/#/get-set/month/)
			var day = $('#' + place + '-day').val(m.date());
			var year = $('#' + place + '-year').val(m.year());
			var hour = $('#' + place + '-hour').val(m.hour());
			var minute = $('#' + place + '-minute').val(m.minute());
			load_date_values(place);
		}

		function load_date_values(place){
			var month = $('#' + place + '-month').val();
			var day = $('#' + place + '-day').val();
			var year = $('#' + place + '-year').val();
			var hour = $('#' + place + '-hour').val();
			var minute = $('#' + place + '-minute').val();
			var timezone = $('#' + place + '-timezone').val();

			var utc = convert_date_to_moment(month, day, year, hour, minute, timezone);
			if (isNaN(utc.unix())){
				$('#' + place).val('');
				$('#' + place + '-local').val('');
				$('#' + place + '-zonetime').val('');
			} else {
				$('#' + place).val(utc.unix());
				$('#' + place + '-local').val(utc.local().format("dddd, MMMM Do YYYY, h:mm:ss a zz"));
				$('#' + place + '-zonetime').val(utc.tz(timezone).format("dddd, MMMM Do YYYY, h:mm:ss a zz"));
			}
		}

		function convert_date_to_moment(month, day, year, hour, minute, timezone){
			var month_num = month.toString();
			if (month_num.length == 1){
				var month_num = "0" + month_num;
			}

			var day_str = day.toString();
			if (day_str.length == 1){
				day_str = "0" + day_str;
			}

			var hour_str = hour.toString();
			if (hour_str.length == 1) {
				hour_str = "0" + hour_str;
			}

			var min_str = minute.toString();
			if (min_str.length == 1) {
				min_str = "0" + min_str;
			}

			// 2013-02-08 24:00
			var date_string = year.toString() + '-' +  month_num + '-' + day_str +' ' + hour_str +':'+ min_str +':00';
			var m = moment(date_string, moment.ISO_8601);
			return m;
		}

		$(function () {
            $('.start-date').change(function () {
                load_date_values('start');
            });

            $('.end-date').change(function () {
                load_date_values('end');
            });

            $('.freeze-date').change(function () {
                load_date_values('freeze');
            });

            $('#export-button').click(function (e) {
                e.preventDefault();
                var segments = [];
                $.each($('.export-config:checked'), function (key, value) {
                    segments.push($(value).val());
                });
                segments = segments.join(',');
                var href = script_root + '/admin/export';
                $('#export-button').attr('href', href + '?segments=' + segments);
                window.location.href = $('#export-button').attr('href');
            });

            $('#import-button').click(function (e) {
                e.preventDefault();
                var segments = [];
                $.each($('.import-config:checked'), function (key, value) {
                    segments.push($(value).val());
                });
                segments = segments.join(',');
                console.log(segments);

                var import_file = document.getElementById('import-file').files[0];
                var nonce = $('#nonce').val();

                var form_data = new FormData();
                form_data.append('segments', segments);
                form_data.append('backup', import_file);
                form_data.append('nonce', nonce);

                $.ajax({
                    url: script_root + '/admin/import',
                    type: 'POST',
                    data: form_data,
                    processData: false,
                    contentType: false,
                    statusCode: {
                        500: function (resp) {
                            console.log(resp.responseText);
                            alert(resp.responseText);
                        }
                    },
                    success: function (data) {
                        window.location.reload()
                    }
                });
            });


			var hash = window.location.hash;
			if (hash) {
				hash = hash.replace("<>[]'\"", "");
				$('ul.nav a[href="' + hash + '"]').tab('show');
			}

			$('.nav-pills a').click(function (e) {
				$(this).tab('show');
				window.location.hash = this.hash;
			});

			var start = $('#start').val();
			var end = $('#end').val();
			var freeze = $('#freeze').val();

			if (start){
				load_timestamp('start', start);
			}
			if (end){
				load_timestamp('end', end);
			}
			if (freeze) {
				load_timestamp('freeze', freeze);
			}

			// Toggle username and password based on stored value
			$('#mail_useauth').change(function () {
				$('#mail_username_password').toggle(this.checked);
			}).change();
		});
	</script>
{% endblock %}
